package fm.admin.controller;

import fm.cache.ConfigCache;
import fm.controller.BaseController;
import fm.exception.BizException;
import fm.mongoService.TokenService;
import fm.sys.token.AdminToken;
import fm.sys.token.MerchantToken;
import fm.web.CurrentRequest;
import fm.web.MediaTypes;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 管理端登陆控制器
 * <p>
 * Created by CM on 17/5/7.
 */
@Controller
@RequestMapping("/admin/login")
public class AdminLoginController extends BaseController {


    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index(ModelMap modelMap, String err_msg) {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return "redirect:/admin/index";
        }
        return "admin/login/login";
    }

    @RequestMapping("/out")
    public void index(HttpServletRequest request, HttpServletResponse response) {
        SecurityUtils.getSubject().logout();
        try {
            WebUtils.issueRedirect(request, response, ConfigCache.getConfig("UI_URL"));
        } catch (IOException e) {
            LOGGER.error("返回首页失败:", e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "loginout", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map loginout() {
        Map res = new HashMap();
        try {
            SecurityUtils.getSubject().logout();
            res.put("flag", true);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("发生错误:", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("发生异常", ex);
            this.failed(res, "服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }

    @RequestMapping("/gomanager")
    public String gomanager(ModelMap modelMap, String token) {

        MerchantToken ticket = new MerchantToken(token);
        Subject subject = SecurityUtils.getSubject();
        subject.login(ticket);

        return "redirect:/admin/index";
    }

    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public String index(HttpServletRequest request, String phone, String vrcd, String pass) {
        try {
            String city = CurrentRequest.getRequest().getRemoteHost();

            if (StringUtils.isNotEmpty(vrcd)) {
                //登录验证码校验
                Subject subject = SecurityUtils.getSubject();
                subject.login(new MerchantToken(phone, vrcd));
            } else if (StringUtils.isNotEmpty(pass)) {
                //密码校验
                Subject subject = SecurityUtils.getSubject();
                subject.login(new AdminToken(phone, pass));
            } else {
                //参数缺失
                return "redirect:/admin/login?err_msg=parameter lost!";
            }
        } catch (UnknownAccountException ex) {
            return "redirect:/admin/login?err_msg=account/password invalid";
        } catch (Exception ex) {
            LOGGER.error("登录发生错误：", ex);
            return "redirect:/admin/login?err_msg=" + ex.getMessage();

        }

        return "redirect:/admin/index";
    }

    @Autowired
    TokenService tokenService;

    @ResponseBody
    @RequestMapping(value = "/auth", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map tokenAuth(String phone, String vrcd) {
        Map res = new HashMap();
        try {
            if (StringUtils.isNotEmpty(phone) && StringUtils.isNotEmpty(vrcd)) {
                //登录验证码校验
                Subject subject = SecurityUtils.getSubject();
                subject.login(new MerchantToken(phone, vrcd));
                if (subject.isAuthenticated()) {
                    String token = tokenService.buildToken(getCurrentUserId(), null);
                    res.put("data", token);
                    this.success(res);
                } else {
                    throw new BizException("请正确填写手机号码与短信验证码!");
                }
            } else {
                throw new BizException("请正确填写手机号码与短信验证码!");
            }

        } catch (BizException ex) {
            LOGGER.error("发生错误:", ex);
            this.failed(res, ex.getMessage());
        } catch (UnknownAccountException ex) {
            LOGGER.error("发生错误:", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("发生异常", ex);
            this.failed(res, "服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }


}
